#include "socket_zmq.h"

/*
 *  socket      对应通信socket
 *  send_buffer 待发送数据
 *  bufferLen   待发送数据长度
 */
int zmq_Send(void *socket, char *send_buffer, int send_bufferLen)
{
    int rc = zmq_send (socket, send_buffer, send_bufferLen + 1, 0);
    if(rc = send_bufferLen + 1)
    {
        return ZMQ_SUCCESS;
    } else {
        printf(" Error: Send Failed! \n");
        return ERROR_SEND_ERROR;
    }
}

/*
 *  socket      对应通信socket
 *  rec_buffer  存数据buffer，长度为3360
 */
int zmq_Receive(void *socket, char *rec_buffer)
{
    memset(rec_buffer, 0, 3360);
    int rc = zmq_recv (socket, rec_buffer, 3360, 0);
    if(rc > 0 && rc < 3360)
    {
        return ZMQ_SUCCESS;
    } else {
        // printf(" Receive Waiting! \n");
        // printf("inner 4\n");
        return ERROR_RECEIVE_ERROR;
    }
}

/*
 *  ipset       需要通信的Server对象ip，固定格式 "tcp://" + ip + ":" + port
 *  send_buffer 待发送数据
 *  bufferLen   待发送数据长度
 *  rec_buffer  存数据buffer
 */
int zmq_Client(char *ipset, char *send_buffer, int send_bufferLen, char *rec_buffer)
{
    void * pCtx = NULL;
    void * pSock = NULL;

    if((pCtx = zmq_ctx_new()) == NULL)
    {
        printf("Error: Socket MainServer zmq_ctx_new() wrong! \n");
        return ERROR_CLIENT_ERROR;
    }
    // printf("step 1\n");
    // 一对一通信模式 Server REP, Client REQ
    if((pSock = zmq_socket(pCtx, ZMQ_REQ)) == NULL)
    {
        printf("Error: Socket MainServer zmq_socket() wrong! \n");
        zmq_ctx_destroy(pCtx);
        return ERROR_CLIENT_ERROR;
    }
    // printf("step 2\n");

    if(zmq_connect(pSock, ipset) < 0)
    {
        printf("Error: Socket MainServer zmq_bind() wrong! \n");
        zmq_close(pSock);
        zmq_ctx_destroy(pCtx);
        return ERROR_CLIENT_ERROR;
    }
    // printf("step 3\n");

    // 设置超时机制
    int timeout = 20000;
    zmq_setsockopt (pSock, ZMQ_SNDTIMEO, &timeout, sizeof(timeout));
    zmq_setsockopt (pSock, ZMQ_RCVTIMEO, &timeout, sizeof(timeout));

    if(zmq_Send(pSock, send_buffer, send_bufferLen) != ZMQ_SUCCESS)
    {
        printf("\nsend error\n");
        return ERROR_SEND_ERROR;
    }
    // printf("step 4\n");
    
    // int t = zmq_Receive(pSock, rec_buffer);
    // printf("t = %d\n", t);
    if(zmq_Receive(pSock, rec_buffer) != ZMQ_SUCCESS)
    {
        printf("\nreceive error\n");
        return ERROR_RECEIVE_ERROR;
    }
    // else{
    //     printf("step 4-1\n");
    // }
    // printf("step 5\n");
    zmq_close(pSock);

    // printf("step 6\n");
    zmq_ctx_destroy(pCtx);
    return ZMQ_SUCCESS;
}
